import requests
import json
import re
import execjs

class BaiduFanyi:
    def __init__(self,trans_str):
        self.url = "https://fanyi.baidu.com/?aldtype=16047#auto/zh"
        self.trans_str = trans_str
        self.detect_url = "https://fanyi.baidu.com/langdetect"
        self.trans_url = "https://fanyi.baidu.com/basetrans"
        self.headers = {
            "User-Agent":"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36",
            "cookie":"PSTM=1575250272; BAIDUID=4C46E632BF98662F1A6CB18F95A3F7FB:FG=1; BIDUPSID=ADE465ECF0D764631672BA8508421928; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDUSS=lVONUQ5ZmxsZXJBU0JJTzhXY3JQMGV4NDlYNjdNTGpPbjBhYlMyVVF4WVBrU2xlRVFBQUFBJCQAAAAAAAAAAAEAAABC9QCkbmxibDczAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8EAl4PBAJeN; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; APPGUIDE_8_2_2=1; from_lang_often=%5B%7B%22value%22%3A%22rom%22%2C%22text%22%3A%22%u7F57%u9A6C%u5C3C%u4E9A%u8BED%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D; delPer=0; H_PS_PSSID=1430_21122_30210_30492_30412_30284_26350_30504; PSINO=1; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1577495322,1577495335; __yjsv5_shitong=1.0_7_3ce0880c347c9d1b79eeb4fccc02db491439_300_1577495287132_111.20.226.17_b9c3bb11; to_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; Hm_lvt_afd111fa62852d1f37001d1f980b6800=1577496539; Hm_lpvt_afd111fa62852d1f37001d1f980b6800=1577496582; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1577496582; yjs_js_security_passport=76f0589108d51cc7878a32269996b75cc5117d6e_1577496535_js"
        }

    def parse_url(self,url):
        r = requests.get(url,headers=self.headers)
        return r.content.decode()

    def get_baidu_sign(self):
        with open("baidusign.js") as f:
            jsData = f.read()
            sign = execjs.compile(jsData).call("e", self.trans_str)
            return sign


    def post_url(self,post_url,post_data): #发送post请求，获取响应，处理成字典
        r = requests.post(post_url,data=post_data,headers=self.headers)
        return json.loads(r.content.decode())

    def get_ret(self,dict_response): #提取翻译结果
        ret = dict_response["trans"][0]["dst"]
        print("翻译结果：",ret)

    def run(self): #实现主要逻辑
        # 1.检测语言类型
        # 1.1 准备post的url地址，post_data
        lang_detect_data = {"query": self.trans_str}
        # 1.2 发送post请求，获取响应
        lan = self.post_url(self.detect_url,lang_detect_data)["lan"]
        # 1.3 提取语言类型
        # 2.准备post的数据，发起响应
        # 2.1 获取token的值
        r1 = self.parse_url(self.url)
        token = re.findall("token: '(.*?)',",r1)[0]
        # print("token:",token)
        # 2.2 获取sign的值
        sign = self.get_baidu_sign()
        trans_data = {
            "query":self.trans_str,
            "from":"zh",
            "to":"en",
            "token":token,
            "sign":sign,
        } if lan == "zh" else {
            "query":self.trans_str,
            "from":"en",
            "to":"zh",
            "token":token,
            "sign":sign,
        }
        # 3.发送请求，获取响应
        dict_response = self.post_url(self.trans_url,trans_data)
        # 4.提取翻译的结果
        self.get_ret(dict_response)

if __name__ == '__main__':
    trans_str = input("待翻译：")
    baidufanyi = BaiduFanyi(trans_str)
    baidufanyi.run()